package cn.tedu.zookeeper;


import org.apache.zookeeper.*;
import org.apache.zookeeper.data.Stat;
import org.junit.Before;
import org.junit.Test;

import java.io.IOException;
import java.util.List;
import java.util.concurrent.CountDownLatch;

public class ZookeeperDemo1 {
    private ZooKeeper zk;
    //连接Zookeeper
    //zookeeper所有的连接和请求过程都是基于Netty来完成的
    //netty是基于NIO的异步非阻塞的通信框架
    //异步：测试线程和连接线程之间可以互相抢占的
    //非阻塞：无论是否建立连接 测试线程都可以先抢占往下执行
    @Before
    public void connect() throws IOException, InterruptedException {
        CountDownLatch cdl = new CountDownLatch(1);
        //参数 ip:port 会话超时时间 监控者，监控连接是否建立
        zk = new ZooKeeper("10.42.77.153:2181",
                5000,//现阶段要求范围在4000-40000之间
                e ->{
                    if (e.getState() == Watcher.Event.KeeperState.SyncConnected)
                        System.out.println("连接成功");
                    cdl.countDown();

                }


        );
        //需要等上面的线程线程执行完毕，才能继续往下执行
        cdl.await();
        System.out.println("finish");
    }
    //创建节点
    @Test
    public void createNode() throws KeeperException, InterruptedException {
        String path = zk.create("/log","data=2020-10-27".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
        System.out.println(path);
    }
    //修改节点数据
    @Test
    public void setData() throws KeeperException, InterruptedException {
        Stat s = zk.setData("/log", "size=10240".getBytes(), -1);
        System.out.println(s);
    }
    //获取数据
    @Test
    public void getData() throws KeeperException, InterruptedException {
        byte[] data = zk.getData("/log", null, new Stat());
        byte[] data2 = zk.getData("/log", null, null);
        System.out.println(new String(data));
    }
    //获取节点子节点
    @Test
    public void getChildren() throws KeeperException, InterruptedException {
        List<String> children = zk.getChildren("/", null);
        for (String c : children
             ) {
            System.out.println(c);
        }
    }
    //删除节点
    @Test
    public void deleteNode() throws KeeperException, InterruptedException {
        zk.delete("/log",-1);
    }
    //判断节点是否存在
    @Test
    public void exist() throws KeeperException, InterruptedException {
        Stat exists = zk.exists("/log", null);
        System.out.println(exists);
    }
}
